package com.jack.payment.rabbitmq.consumer;

import com.jack.payment.dao.user.UserDeviceDao;
import com.jack.payment.dao.user.UserSettingDao;
import com.jack.payment.entity.filter.UserFilter;
import com.jack.payment.entity.generate.user.UserDeviceModel;
import com.jack.payment.entity.generate.user.UserSettingModel;
import com.jack.payment.rabbitmq.constant.RabbitmqConstant;
import com.jack.payment.rabbitmq.entity.QueueContentModel;
import com.jack.payment.rabbitmq.produer.MQSender;
import com.jack.payment.service.mongo.QueueLogServiceImpl;
import com.jack.payment.util.common.StringUtil;
import com.jack.payment.util.common.TimeUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
public class LoginSuccessReceiver {
    private Logger log = LoggerFactory.getLogger(LoginSuccessReceiver.class);

    @Autowired
    private QueueLogServiceImpl queueLogService;
    @Autowired
    private UserSettingDao userSettingDao;
    @Autowired
    private UserDeviceDao userDeviceDao;
    @Autowired
    private MQSender mqSender;

    @RabbitListener(queues = RabbitmqConstant.QUEUE_LOGIN)
    public void loginSuccessRecord(Message message,
                                   QueueContentModel<UserDeviceModel> queueModel,
                                   Channel channel) throws IOException {
        log.info("用户登录日志!! 正在进行队列消费!!! 队列id==>>>{}, 消息主题为==>>{} 已消费了==>>{}次",
                queueModel.getId(), queueModel.getSubject(), queueModel.getCount());
        Long currentTime = TimeUtil.getCurrentTime();
        Integer count = queueModel.getCount();
        queueModel.setCount( count + 1);
        try {
            if (queueModel.getStatus() == 0) {
                userAttachData(queueModel.getData());
                queueModel.setStatus(1);
                queueModel.setSuccessDate(currentTime);
            }
        }catch (Exception e) {
            log.error("登录设备记录失败!!!" + e);
            log.error("队列id=>>{}, 对应集合=>>{}", queueModel.getId(), queueModel.getDbName());
            queueModel.setExceptionInfo(e.getMessage());
            if (count < 2 && queueModel.getIsManual() == 0) {
                log.info("消息消费失败!!! 正在进行重发, 当前已发送{}次, 总共发送2次", count);
                mqSender.sendMQMessage(
                        queueModel.getExchange(),
                        queueModel.getQueueName(),
                        queueModel
                );
            }
        } finally {
            queueModel.setLastDate(currentTime);
            queueLogService.updateQueueLog(queueModel, queueModel.getDbName());
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


    /**
     * 用户附加数据的 验证 与 写入
     * @param userDeviceModel
     */
    private void userAttachData(UserDeviceModel userDeviceModel) {
        // 只有登录时才进行数据操作
        if (!StringUtil.isEmpty(userDeviceModel.getUserId())
                && !StringUtil.isEmpty(userDeviceModel.getDeviceId())) {
            UserFilter.UserDeviceFilter userDeviceFilterModel = new UserFilter.UserDeviceFilter();

            userDeviceFilterModel.setUserId(userDeviceModel.getUserId());
            userDeviceFilterModel.setDeviceId(userDeviceModel.getDeviceId());

            List<UserDeviceModel> userDeviceModelList = userDeviceDao.getAppointUserBindDeviceList(
                    userDeviceFilterModel
            );
            if (userDeviceModelList.isEmpty()) {
                userDeviceModel.setDeviceIcon(getDeviceIcon(userDeviceModel.getDeviceModel()));
                userDeviceModel.setCreateTime(userDeviceModel.getLastOneTime());
                userDeviceDao.insertUserDeviceInfo(userDeviceModel);
            } else {
                UserDeviceModel deviceModel = new UserDeviceModel().builder()
                        .userId(userDeviceModel.getUserId())
                        .deviceId(userDeviceModel.getDeviceId())
                        .lastOneTime(userDeviceModel.getLastOneTime())
                        .ipAddress(userDeviceModel.getIpAddress())
                        .build();
                if (userDeviceModelList.get(0).getEnable() == 0) {
                    deviceModel.setEnable(1);
                }
                userDeviceDao.updateUserDeviceInfo(deviceModel);
            }
        }
        if (!StringUtil.isEmpty(userDeviceModel.getUserId())) {
            UserSettingModel userSettingModel = new UserSettingModel();
            userSettingModel.setUserId(userDeviceModel.getUserId());
            userSettingModel.setLastOneTime(userDeviceModel.getLastOneTime());
            userSettingModel.setIpAddress(userDeviceModel.getIpAddress());
            userSettingDao.updateAppointUserSetting(userSettingModel);
        }
    }

    /**
     * 获取设备的图标
     * @param deviceMethod
     * @return
     */
    private String getDeviceIcon(String deviceMethod) {
        String suffixPath = "pay/svg/";
        if (deviceMethod.startsWith("Android")) {
            return suffixPath + "android.svg";
        }
        if (deviceMethod.startsWith("Windows")) {
            return suffixPath + "windows.svg";
        }
        if (deviceMethod.startsWith("iOS") || deviceMethod.startsWith("MacOS")) {
            return suffixPath + "apple.svg";
        }
        return suffixPath + "devices.svg";
    }
}
